import time
from datetime import datetime, timedelta
from collections import deque
from 新版2.系统组件.基础配置 import settings
from 新版2.系统组件.数据库 import data_curd

class UpDown:

    def __init__(self):
        self.stock_codes = {stock["all_code"] for stock in settings.STOCK_CODE}
        self.stock_type = {stock["all_code"]: stock["name"] for stock in settings.STOCK_CODE}
        self.historical_data = {code: deque(maxlen=100) for code in self.stock_codes}
        self.fluctuation_status = {code: {"in_range": False, "start_time": "", "updown_id": 0} for code in
                                   self.stock_codes}
        self.data_curd = data_curd()

    def updown_watch_tick(self,stock_code, stock_data):
        current_time = time.time()
        now = datetime.fromtimestamp(current_time).strftime("%H:%M:%S")
        stock_name = self.stock_type.get(stock_code)
        current_price = stock_data[0].get("lastPrice")  # 根据实际API调整字段名

        # 1. 保存当前数据
        self.historical_data[stock_code].append({
            "price": current_price,
            "time": current_time
        })
        # 减少监控输出频率，每50个数据点输出一次
        # if len(self.historical_data[stock_code]) % 50 == 0:
        #     print(f"监控{len(self.historical_data[stock_code])}:{now}-{stock_name}当前价格{current_price}")

        # 2. 检查3分钟内波动（需至少有2个数据点）
        if len(self.historical_data[stock_code]) >= settings.UPDOWN_TIME:
            prices = [item["price"] for item in self.historical_data[stock_code]]
            min_p, max_p = min(prices), max(prices)
            fluctuation = (max_p - min_p) / min_p * 100  # 计算波动百分比

            # 3. 判断波动状态变化
            current_status = self.fluctuation_status[stock_code]
            ##print(f"{now}-{stock_name}当前价格{current_price},最高价格{max_p},最低价格{min_p},当前波动{fluctuation}")

            if fluctuation <= settings.UPDOWN_SPAN:  # 波动≤0.2%
                if not current_status["in_range"]:  # 首次进入范围
                    current_status["in_range"] = True
                    current_status["start_time"] = datetime.fromtimestamp(current_time).strftime("%Y-%m-%d %H:%M:%S")  # 记录开始时间
                    ##记录震荡区间
                    updown_id = self.data_curd.add_updown(stock_code, min_p, max_p, current_time)  ##这里需要记录区间id
                    current_status["updown_id"] = updown_id  # 保存ID到状态
                    msg = f"{stock_name} 进入横盘,低位价格{min_p:.3f}"
                    ##print(msg)
                    # update_stock_updown(stock_code, updown_id)
                    # show_notification_thread("振幅提示", msg)


            else:  # 波动>0.2%
                if current_status["in_range"]:  # 刚从范围内突破
                    duration = current_time - datetime.strptime(current_status["start_time"],"%Y-%m-%d %H:%M:%S").timestamp()
                    ##print(f"[结束] {stock_name} 脱离低波动区间，持续时间: {duration:.1f}秒")
                    self.data_curd.update_updown(current_status["updown_id"], current_time)
                    current_status["in_range"] = False
                    current_status["start_time"] = ""
                    current_status["updown_id"] = 0  # 清除ID
                    msg = f"{stock_name} 脱离横盘"
                    # update_stock_updown(stock_code, 0)
                    # show_notification_thread("振幅提示", msg)
                    ##出波段撤买单
            return current_status["updown_id"]

